package com.byCreation.t_globe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import pl.mg6.android.maps.extensions.ClusterGroup;
import pl.mg6.android.maps.extensions.ClusteringSettings;
import pl.mg6.android.maps.extensions.GoogleMap;
import pl.mg6.android.maps.extensions.Marker;
import pl.mg6.android.maps.extensions.MarkerOptions;
import pl.mg6.android.maps.extensions.SupportMapFragment;

import com.aretha.slidemenu.SlideMenu;
import com.byCreatetion.adabter.GridViewAdapter;
import com.byCreation.Control.Control;
import com.byCreation.Profile.CompareActivity;
import com.byCreation.Profile.MyBookmarkActivity;
import com.byCreation.Profile.MyDiscountActivity;
import com.byCreation.Profile.MyHistoryActivity;
import com.byCreation.Profile.MyNoteActivity;
import com.byCreation.Profile.MySettingActivity;
import com.byCreation.Profile.MyprofileActivity;
import com.byCreation.Profile.TglobeAppActivity;
import com.byCreation.map.DemoClusterOptionsProvider;
import com.byCreation.t_globe.ContentActivity.LoadData2;
import com.byCreation.t_globe.R;



import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;

import Myclass.ConnectInternet;
import Parser.HttpGetJson;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MapActivity extends BaseSlideMenuActivity implements OnClickListener  {

	
	//SliderMenu
	private SlideMenu mSlideMenu;
	
	
	//Profile
	private ImageView img_profile_menu1,img_profile_menu2,img_profile_menu3,
	img_profile_menu4,img_profile_menu5,img_profile_menu6,img_profile_menu7,
	img_profile_menu8,img_profile_menu9,img_user;
	
	private LinearLayout txt_next,txt_register;
	private FrameLayout Laylogin;
	private ConnectInternet connect=new ConnectInternet(MapActivity.this);
	
	
	
	
	
	
	//=========Map
	private GoogleMap mMap;
	private List<Marker> declusterifiedMarkers;
	

		
		
	//=======menu down
	private FrameLayout lay_filter,lay_search,lay_ok_filter,lay_search_n;
	public static LinearLayout lay_cardmenu_down;
	private  Animation anim_downmenu_in,anim_downmenu_out;
	public static Animation anim_downmenu_hide;
	public static boolean isMenuShow=false;
				
	//====Filter GridVeiw
				
	private GridView gridView;
	public  ArrayList<HashMap<String, Object>> MyArrList_grid;
	private HashMap<String, Object> map_grid = new HashMap<String, Object>();
	private GridViewAdapter customGridAdapter;
	
	//====search
	public static LinearLayout lay_search_edittext;
	private FrameLayout lay_filter_n,lay_search_ok;
	public static  FrameLayout lay_alpha;
				
	
	// ===============GoogleAnalytics==============
	private GoogleAnalytics mGaInstance;
	private Tracker mGaTracker;
	// =============================================
		// ===================================googleAnalytics=============================
		@Override
		public void onStart() {
			super.onStart();
			// The rest of your onStart() code.
			EasyTracker.getInstance().activityStart(this); // Add this method.
			mGaTracker.sendView("MapScreen");
		
		}
		
		@Override
		public void onStop() {
			super.onStop();
			// The rest of your onStop() code.
			EasyTracker.getInstance().activityStop(this); // Add this method.

}

// ================================================================================

	
	
	@Override
	public void onContentChanged() {
		super.onContentChanged();
		Log.e("Test", "SlideMenuAttribute");
		
		setSlideRole(R.layout.activity_map);
		setSlideRole(R.layout.layout_primary_menu);
		setSlideRole(R.layout.fagment_profile);
		mSlideMenu = getSlideMenu();

		// =============================GoogleAnalytics=========================
		mGaInstance = GoogleAnalytics.getInstance(this);
		mGaTracker = mGaInstance.getTracker(Control.IDGoogleanalytics);
		
		
		mSlideMenu.setEdgeSlideEnable(true);
		mSlideMenu.setEdgetSlideWidth(Control.setEdgetSlideWidth);
		Display display = getWindowManager().getDefaultDisplay(); 
		int width = display.getWidth();  // deprecated
		int height = display.getHeight();  // deprecated
		
		 RelativeLayout rl = (RelativeLayout) findViewById(R.id.R1);
		 RelativeLayout r2 = (RelativeLayout) findViewById(R.id.R2);
		 
		 rl.getLayoutParams().width = width-100;
		 r2.getLayoutParams().width = width-100;
		 
		 
		
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		
	
		
	
		
		SetView();
		setGridView();
		SetViewProfile();
		
		if(new ConnectInternet(MapActivity.this).checkInternetConnection())
		new Load_MapData().execute();
		
		
		
		
	}
	
	//================SetProfileMenu====================
	
	
	private void SetViewProfile() {
		// TODO Auto-generated method stub
		
		
		Laylogin=(FrameLayout)findViewById(R.id.Laylogin);
		if(!Control.Loginstatus)
			Laylogin.setVisibility(View.VISIBLE);
		
		
		//=======menu
		img_profile_menu1=(ImageView)findViewById(R.id.img_profile_menu1);
		img_profile_menu2=(ImageView)findViewById(R.id.img_profile_menu2);
		img_profile_menu3=(ImageView)findViewById(R.id.img_profile_menu3);
		img_profile_menu4=(ImageView)findViewById(R.id.img_profile_menu4);
		img_profile_menu5=(ImageView)findViewById(R.id.img_profile_menu5);
		img_profile_menu6=(ImageView)findViewById(R.id.img_profile_menu6);
		img_profile_menu7=(ImageView)findViewById(R.id.img_profile_menu7);
		img_profile_menu8=(ImageView)findViewById(R.id.img_profile_menu8);
		img_profile_menu9=(ImageView)findViewById(R.id.img_profile_menu9);
		
		img_user=(ImageView)findViewById(R.id.img_user);
		img_user.setOnClickListener(this);
		
		img_profile_menu1.setOnClickListener(this);
		img_profile_menu2.setOnClickListener(this);
		img_profile_menu3.setOnClickListener(this);
		img_profile_menu4.setOnClickListener(this);
		img_profile_menu5.setOnClickListener(this);
		img_profile_menu6.setOnClickListener(this);
		img_profile_menu7.setOnClickListener(this);
		img_profile_menu8.setOnClickListener(this);
		img_profile_menu9.setOnClickListener(this);

		
		
		//=========Login
		
		

		TextView txt_username=(TextView) findViewById(R.id.txt_username);
		txt_username.setText(Control.UserName);
		
		txt_next=(LinearLayout)findViewById(R.id.txt_next);
		txt_next.setOnClickListener(this);
		
		txt_register=(LinearLayout)findViewById(R.id.txt_register);
		txt_register.setOnClickListener(this);
		
		
		ImageView img_tglobe_login=(ImageView)findViewById(R.id.img_tglobe_login);
		img_tglobe_login.setOnClickListener(this);
		
		ImageView img_facebook =(ImageView)findViewById(R.id.img_facebook);
		img_facebook.setOnClickListener(this);
		
		
		if (Control.Loginstatus)
		{
			Log.e("Picasso", "=========Picasso() ==========");
			try {
				
				
				
				Log.e("Picasso", "=========Picasso() ==========");
				
				if(Control.Img_profile.equals(""))
				{
					img_user.setImageResource(R.drawable.btn_menu_top_righ);

				}
				else
				{
					Bitmap myBitmap = BitmapFactory.decodeFile(Control.Img_profile_Path);
					img_user.setImageBitmap(myBitmap);

				}
				
				
				
				} catch (Exception e) {
					img_user.setImageResource(R.drawable.btn_menu_top_righ);

				}
		}
		
		
		
	}







	@Override
	public void onClick(View v) {
		
		if(v.getId()==R.id.img_profile)
		{
			mSlideMenu.open_R(true, true);

		}
		else
		if(v.getId()==R.id.img_mainmenu)
		{
			mSlideMenu.open_L(true, true);

		}
		
		
		//down menu
				if(v.getId()==R.id.lay_filter)
				{
					
					HideSearch();
					ShowFilter();
				}
				else
				if(v.getId()==R.id.lay_search)
				{
					
					HideFilter();
					ShowSearch();
				}
				else
				if(v.getId()==R.id.lay_ok_filter)
				{
					
					HideFilter();
					// Filter Call API
				}
				else
				if(v.getId()==R.id.lay_search_n)
				{
					
					HideFilter();
					ShowSearch();
				}
				else
				if(v.getId()==R.id.lay_search_ok)
				{
					HideSearch();
					
					//====Search  Text Call API
					
				}
				else
				if(v.getId()==R.id.lay_filter_n)
				{
					
					
					HideSearch();
					ShowFilter();
					
					
				}
				if(v.getId()==R.id.lay_alpha)
				{
					HideSearch();
					HideFilter();
				}

		
		
		
		
		
		
		//======Profile
//		//================Menu==============
		
		
		
				if(v.getId()==R.id.img_profile_menu1)
				{
					startActivity(new Intent(MapActivity.this,MyHistoryActivity.class));
				}
				if(v.getId()==R.id.img_profile_menu2)
				{
					startActivity(new Intent(MapActivity.this,MyBookmarkActivity.class));
				}
				if(v.getId()==R.id.img_profile_menu3)
				{
					startActivity(new Intent(MapActivity.this,MyNoteActivity.class));
				}
				if(v.getId()==R.id.img_profile_menu4)
				{
					//startActivity(new Intent(MainActivity.this,MyCompareActivity.class));
					startActivity(new Intent(MapActivity.this,CompareActivity.class));
					
				}
				if(v.getId()==R.id.img_profile_menu5)
				{
					startActivity(new Intent(MapActivity.this,MyNoteActivity.class));
				}
				if(v.getId()==R.id.img_profile_menu6)
				{
					startActivity(new Intent(MapActivity.this,TglobeAppActivity.class));
				}
				
				if(v.getId()==R.id.img_profile_menu7)
				{
					startActivity(new Intent(MapActivity.this,MyDiscountActivity.class));
				}
				if(v.getId()==R.id.img_profile_menu8)
				{
					startActivity(new Intent(MapActivity.this,MySettingActivity.class));
				}
				if(v.getId()==R.id.img_profile_menu9)
				{
					Control.Loginstatus=false;
					MapActivity.this.finish();
					startActivity(new Intent(MapActivity.this,LoginActivity.class));
				}

				
				
				if(v.getId()==R.id.img_user)
				{

					startActivity(new Intent(MapActivity.this,MyprofileActivity.class));
				}
				
		//===============
	}
	
	
	
	
	
	private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
        	//mMap.clear();
        	setUpMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
            	
            }
        }
    }
	
    private void setUpMap() {
    	
    	
    	 Log.e("Map", "==========setUpMap()========");
		/*if(MyArrList.size()>0)
		mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Double.parseDouble(MyArrList.get(0).get("latitude").toString()), Double.parseDouble( MyArrList.get(0).get("longitude").toString())), 10.0f));*/
    	FragmentManager fm =  getSupportFragmentManager();
    	SupportMapFragment f = (SupportMapFragment) fm.findFragmentById(R.id.map);
		mMap = f.getExtendedMap();
		 
		 
			
		final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(14.447573, 100.325553), 5));
        
		
		
		
		mSlideMenu.close(true);
		
		 if (mapView.getViewTreeObserver().isAlive()) {
	         
			 mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
	                
	                @SuppressLint("NewApi")
					@Override
	                public void onGlobalLayout() {
	                    
	                	
	                	
	                	
	                	  LatLngBounds.Builder builder = new LatLngBounds.Builder();
	                	  LatLngBounds tmpBounds = null;
	                	  int i=0;
	                	  while(i<MyArrList.size())
	                	  {
	                	    builder.include(new LatLng(Double.parseDouble(MyArrList.get(i).get("latitude").toString()), Double.parseDouble( MyArrList.get(i).get("longitude").toString())));
	                	    tmpBounds = builder.build();
	                	    i++;
	                	    Log.e("Map", "==========i<MyArrList.size()=========");
	                	  }
                        
	                    
	                    
	                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
	                      mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
	                    } else {
	                      mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
	                    }
	                    mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(tmpBounds, 50));
	                    
	                    Log.e("Map", "==========moveCamera=========");
	                }
	            });
	        }
		 else
			 Toast.makeText(this, "! mapView.getViewTreeObserver().isAlive()",300).show();
		
		
		mMap.setClustering(new ClusteringSettings().clusterOptionsProvider(new DemoClusterOptionsProvider(getResources())));
		
		addMarkers(mMap);

		mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
			@Override
			public boolean onMarkerClick(Marker marker) {
				if (marker.isCluster()) {
					declusterify(marker);
					return true;
				}
				return false;
			}
		});
		mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
			@Override
			public void onMapClick(LatLng position) {
				clusterifyMarkers();
			}
		});
        
        
    }
	
	
    public void setGridView() {

		
		gridView = (GridView)findViewById(R.id.gridView1);
	if (MyArrList_grid == null)
		MyArrList_grid = new ArrayList<HashMap<String, Object>>();
	
	
	if(new ConnectInternet(MapActivity.this).checkInternetConnection())
	new LoadFilter().execute();
	
}
	private void SetView() {
		// ===========top menu
		ImageView img_mainmenu = (ImageView)findViewById(R.id.img_mainmenu);
		img_mainmenu.setOnClickListener(this);
		ImageView img_profile = (ImageView)findViewById(R.id.img_profile);
		img_profile.setOnClickListener(this);
		ImageView img_home = (ImageView)findViewById(R.id.img_home);
		img_home.setOnClickListener(this);
		
		
		
		
		 
		//==========menu down
		 lay_filter=(FrameLayout)findViewById(R.id.lay_filter);
		 lay_filter.setOnClickListener(this);
		 lay_search=(FrameLayout)findViewById(R.id.lay_search);
		 lay_search.setOnClickListener(this);
		 lay_search_n=(FrameLayout)findViewById(R.id.lay_search_n);
		 lay_search_n.setOnClickListener(this);
		 lay_filter_n=(FrameLayout)findViewById(R.id.lay_filter_n);
		 lay_filter_n.setOnClickListener(this);
		 lay_search_ok=(FrameLayout)findViewById(R.id.lay_search_ok);
		 lay_search_ok.setOnClickListener(this);
		 
		 
		 
		 lay_ok_filter=(FrameLayout)findViewById(R.id.lay_ok_filter);
		 lay_ok_filter.setOnClickListener(this);
		 
		 
		 
		 lay_search_edittext=(LinearLayout)findViewById(R.id.lay_search_edittext);
		 lay_alpha=(FrameLayout)findViewById(R.id.lay_alpha);
		 lay_alpha.setOnClickListener(this);
		 lay_cardmenu_down=(LinearLayout)findViewById(R.id.lay_cardmenu_down);
		 anim_downmenu_in = AnimationUtils.loadAnimation(MapActivity.this, R.anim.anim_downmenu_show);
		 anim_downmenu_out= AnimationUtils.loadAnimation(MapActivity.this, R.anim.anim_downmenu_hide);
		 anim_downmenu_hide= AnimationUtils.loadAnimation(MapActivity.this, R.anim.anim_downmenu_hide);
		 
		
		
	}

	
	private void ShowFilter() {
		// TODO Auto-generated method stub
		
		if(lay_cardmenu_down.getVisibility()==View.INVISIBLE)
		{
			Log.e("TG", "ShowFilter()");
			isMenuShow=true;
			lay_cardmenu_down.setVisibility(View.VISIBLE);
			lay_alpha.setVisibility(View.VISIBLE);
		
			
			lay_cardmenu_down.startAnimation(anim_downmenu_in);
		}
	}
	
	private void HideFilter() {
		// TODO Auto-generated method stub
		
		if(lay_cardmenu_down.getVisibility()==View.VISIBLE)
		{
			Log.e("TG", "HideFilter()");
			lay_cardmenu_down.startAnimation(anim_downmenu_hide);
			lay_cardmenu_down.setVisibility(View.INVISIBLE);
			lay_alpha.setVisibility(View.INVISIBLE);
			
			isMenuShow=false;
		}
	}
	
	private void HideSearch() {
		// TODO Auto-generated method stub
		if(lay_search_edittext.getVisibility()==View.VISIBLE)
		{
			
			Log.e("TG", "HideSearch()");
			lay_alpha.setVisibility(View.INVISIBLE);
			lay_search_edittext.setVisibility(View.INVISIBLE);
			lay_search_edittext.startAnimation(anim_downmenu_hide);
			isMenuShow=false;
		}
	}
	
	private void ShowSearch() {
		// TODO Auto-generated method stub
		if(lay_search_edittext.getVisibility()==View.INVISIBLE)
		{
			
			Log.e("TG", "ShowSearch()");
			lay_alpha.setVisibility(View.VISIBLE);
			lay_search_edittext.setVisibility(View.VISIBLE);
			lay_search_edittext.startAnimation(anim_downmenu_in);
			isMenuShow=true;
		}
	}
	
	
	
	//==========map
		private void declusterify(Marker cluster) {
			/*clusterifyMarkers();
			declusterifiedMarkers = cluster.getMarkers();
			LatLng clusterPosition = cluster.getPosition();
			double distance = calculateDistanceBetweenMarkers();
			double currentDistance = -declusterifiedMarkers.size() / 2 * distance;
			for (Marker marker : declusterifiedMarkers) {
				marker.setData(marker.getPosition());
				marker.setClusterGroup(ClusterGroup.NOT_CLUSTERED);
				LatLng newPosition = new LatLng(clusterPosition.latitude, clusterPosition.longitude + currentDistance);
				marker.animatePosition(newPosition);
				currentDistance += distance;
			}*/
		}

		private double calculateDistanceBetweenMarkers() {
			Projection projection = mMap.getProjection();
			Point point = projection.toScreenLocation(new LatLng(0.0, 0.0));
			point.x += getResources().getDimensionPixelSize(R.dimen.distance_between_markers);
			LatLng nextPosition = projection.fromScreenLocation(point);
			return nextPosition.longitude;
		}

		private void clusterifyMarkers() {
			if (declusterifiedMarkers != null) {
				for (Marker marker : declusterifiedMarkers) {
					LatLng position = (LatLng) marker.getData();
					marker.setPosition(position);
					marker.setClusterGroup(ClusterGroup.DEFAULT);
				}
				declusterifiedMarkers = null;
			}
		}
		

		class LoadFilter extends AsyncTask<Object, Integer, Object> {

			
			boolean Cancelled=false;
			
			
			@Override
			protected void onCancelled() {
				// TODO Auto-generated method stub]
				Cancelled=true;
				super.onCancelled();
			}
			
			
			@SuppressWarnings("null")
			@Override
			protected Object doInBackground(Object... params) {

					for (int i = 0; i <9; i++)
					{
						
						Log.e("TG", "i="+i);
						 map_grid = new HashMap<String, Object>();
						 MyArrList_grid.add(map_grid);
						
					}

				return null;
			}

			@Override
			protected void onPreExecute() {

				MyArrList_grid.clear();
				customGridAdapter = new GridViewAdapter(MapActivity.this, R.layout.row_grid_card,MyArrList_grid);
				gridView.setAdapter(customGridAdapter);
				
				
				super.onPreExecute();
			}

			@Override
			public void onProgressUpdate(Integer... progress) {
				Log.e("star", "progressupdate");

			}

			@Override
			protected void onPostExecute(Object result) {
				
				if(Cancelled)
				{
					MapActivity.this.runOnUiThread (new Thread(new Runnable() { 
				         public void run() {
				        	 customGridAdapter.notifyDataSetChanged();  
				        	 Log.e("TG","customGridAdapter.notifyDataSetChanged(); ");
				        	 
				        	 
				         }
				     }));
				}
			}

		}

		
		
		
		
		private ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>();
		private HashMap<String, Object> map = new HashMap<String, Object>();
		//======Call API
		class Load_MapData extends AsyncTask<Object, Integer, Object> {

		    private ProgressDialog mProgressDialog;
			private String title,content,images,date,link,result,desc;
			
			
			boolean Cancelled=false;
			
			
			@Override
			protected void onCancelled() {
				// TODO Auto-generated method stub]
				Cancelled=true;
				super.onCancelled();
			}
			
			@SuppressWarnings("null")
			@Override
			protected Object doInBackground(Object... params) {

				try {
					
					
					if(Control.Pointers.equals("Content"))
					{
						JSONObject jsonObj=null;
						
						Log.e("TG", "Control.page_id"+Control.page_id);
					
						jsonObj = new JSONObject(HttpGetJson.GetJson(Control.getAPI_Map(Control.page_id),Control.user,Control.pass));
						
						desc=jsonObj.getString("result");
						JSONArray MapJsonArray=jsonObj.getJSONArray("map");
	
						for (int i = 0; i <MapJsonArray.length(); i++)
						{
							
							JSONObject jsonObj_content=MapJsonArray.getJSONObject(i);
							map = new HashMap<String, Object>();
							
							try {map.put("name", jsonObj_content.getString("name").toString());} catch (JSONException e) {Toast.makeText(MapActivity.this,"Error="+e.toString(), 900).show();}
							try {map.put("latitude",jsonObj_content.getString("latitude").toString());} catch (JSONException e) {Toast.makeText(MapActivity.this,"Error="+e.toString(), 900).show();}
							try {map.put("longitude",jsonObj_content.getString("longitude").toString());} catch (JSONException e) {Toast.makeText(MapActivity.this,"Error="+e.toString(), 900).show();}
						
							
							Log.e("tg", jsonObj_content.getString("name").toString()+" "+jsonObj_content.getString("latitude").toString()+" "+jsonObj_content.getString("longitude").toString());

							MyArrList.add(map);
	
						}
					}
					else if(Control.Pointers.equals("CardDetail"))
					{
						map = new HashMap<String, Object>();
						
						try {map.put("name",CardDetailActivity.MapTitle);} catch (Exception e) {Toast.makeText(MapActivity.this,"Error="+e.toString(), 900).show();}
						try {map.put("latitude",CardDetailActivity.latlng.latitude);} catch (Exception e) {Toast.makeText(MapActivity.this,"Error="+e.toString(), 900).show();}
						try {map.put("longitude",CardDetailActivity.latlng.longitude);} catch (Exception e) {Toast.makeText(MapActivity.this,"Error="+e.toString(), 900).show();}

						MyArrList.add(map);
						desc="success";
					}
					else if(Control.Pointers.equals("CardActivity"))
					{
						map = new HashMap<String, Object>();
						Log.e("TG", "==========Control.Pointers.equals CardActivity==========");
						
						try {map.put("name",CardActivity.titlemap);} catch (Exception e) {e.printStackTrace();}
						try {map.put("latitude",CardActivity.latitude);} catch (Exception e) {e.printStackTrace();}
						try {map.put("longitude",CardActivity.longitude);} catch (Exception e) {e.printStackTrace();}

						MyArrList.add(map);
						desc="success";
					}
					

					
					
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			}
			catch (Exception e) {
					// TODO Auto-generated catch block
				e.printStackTrace();
					
			}
				
			
					 
				return null;
			}

			@Override
			protected void onPreExecute() {

				 //=====================ProgressDialog==========================
		        mProgressDialog = new ProgressDialog(MapActivity.this);
		        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);         
		        mProgressDialog.setMessage("Loading......");                       
		    	mProgressDialog.setCancelable(true);
			
				
				if(mProgressDialog!=null)
					mProgressDialog.show();
				
				
				
				super.onPreExecute();
			}

			@Override
			public void onProgressUpdate(Integer... progress) {

				Log.e("star", "progressupdate");
				
				
			}

			@Override
			protected void onPostExecute(Object result) {
				//Toast.makeText(MapActivity.this, desc, 800).show();
				
				if(!Cancelled)
				{
					try {
					
					if(desc.equals("success"))
						setUpMapIfNeeded();
					} catch (Exception e) {
					// TODO: handle exception
					Toast.makeText(MapActivity.this, e.toString(), 800).show();

					}
				
				
				
				
					if(mProgressDialog!=null)
						mProgressDialog.hide();
				}
			}

		}

		
		public  void addMarkers(GoogleMap map) {
			MarkerOptions options = new MarkerOptions();
			
			
			int i=0;
			while(i<MyArrList.size())
			{
				map.addMarker(options
			
						.title(MyArrList.get(i).get("name").toString())
						.position(new LatLng(Double.parseDouble(MyArrList.get(i).get("latitude").toString()), Double.parseDouble( MyArrList.get(i).get("longitude").toString()))));
						
				
				
				i++;
			}

		}
		
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
		    if (keyCode == KeyEvent.KEYCODE_BACK) {
		        
		    //	moveTaskToBack(true);
		    	finish();
		    	
		    	
		        return true;
		    }
		    return super.onKeyDown(keyCode, event);
		}
	
}
